
var dataMap = {}; //保存性能图和数据库图的数据

//ZTree模板样
var setting = {
    data : {
        key : {
            url : "u"
        },
        simpleData : {
            enable : true
        }
    },
    callback : {
        onClick : onClick
    }
};

$(function() {
    //初始化数据
    initData();
    //点击查询按钮时，创建图片
    $(".press_btn1").click(function() {
        onClick();
    });

})

/**
 * 点击树节点，显示该类型下的设备，并展示用户定制的要显示的列
 * @param event
 * @param treeId
 * @param treeNode
 * @param clickFlag
 */
function onClick(event, treeId, treeNode, clickFlag) {
    var selectNode = getSelectNode();//先获取选中的资源节点
    if (selectNode == null) {
        return;
    }
    if (selectNode.isParent) {
        layer.msg("当前选择为业务系统，请选择业务资源!", {time: 2000});
        return;
    }
    var resource_id = selectNode.id;
    //1 ping代码处理
    dealPing(resource_id);
    //2 性能处理
    dealperfData(resource_id);
    //3 容量处理
    dealCapacData(resource_id);
    //4 进程处理
    dealProcessData(resource_id);
    //5 服务状态处理
    dealServiceStateData(resource_id);
    //6 部件状态
    dealStatusData(resource_id);
    //7 处理数据库状态
    dealDBData(resource_id);
}

//处理ping
function dealPing(resource_id) {
    $("#home").empty();
    var startTime = $("#startTime").val().trim();
    var endTime = $("#endTime").val().trim();
    var url = webPath + "/radar/view/showPingGraph.do?resourceId=" + resource_id
              +"&startTime=" + startTime
              +"&endTime=" + endTime;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = "blob";
    xhr.setRequestHeader("client_type", "DESKTOP_WEB");
    xhr.onload = function () {
        if (this.status == 200) {
            var blob = this.response;
            var img = document.createElement("img");
            img.onload = function(e) {
                window.URL.revokeObjectURL(img.src);
            };
            img.src = window.URL.createObjectURL(blob);
            $("#home").html(img);
        }else if (this.status == 201) {
            $("#home").append("暂无数据");
        }
    }
    xhr.send();
// $.ajax({
    //     url : webPath + "/radar/view/selectPingData.do",
    //     type : "post",
    //     dataType : "json",
    //     data : {
    //         "resourceId" : resource_id,
    //         "startTime" : startTime,
    //         "endTime" : endTime
    //     },
    //     success : function (json) {
    //         var code = json.code;
    //         if (code == "201"){
    //             layer.msg("暂无ping数据", {time: 2000});
    //         }else if (code == "200"){
    //             var results = json.data;
    //             $("#home").append('<div id="ping" style="height: 200px; width:600px;float:left;"></div>');
    //             drawPingImage(results);
    //         }
    //     }
    // });
}

//处理性能
function dealperfData(resource_id){
    $("#perf").empty();
    var startTime = $("#startTime").val().trim();
    var endTime = $("#endTime").val().trim();
    $.ajax({
        url : webPath + "/radar/view/selectPerfData.do",
        type : "post",
        dataType : "json",
        data : {
            "resourceId" : resource_id,
            "startTime" : startTime,
            "endTime" : endTime
        },
        success : function (json) {
            var code = json.code;
            if (code == "201") {
                $("#perf").append("暂无数据");
            }else if (code == "200") {
                var map = json.data;
                $.each(map, function (bcode, monitorViewVos) {

                    //1.页面展示
                    var bcodeName = monitorViewVos[0].bcodeName + "  单位：" + monitorViewVos[0].unit;
                    var html = '<li class="capacity_list"><div class="graph_title"> <h2 style="margin: 0 10px">' + bcodeName + '</h2> <div class="graph_select"> <span class="selectlist">实例<a class="top_current down"></a></span> <ul>';
                    var subMonitorViewVos = [];
                    var flag = 0;
                    //2.如果bcode下面有多个piId，只展示一个
                    $.each(monitorViewVos, function (i, vo) {
                        html += "<li key='" + bcode+"<|>"+ vo.piId + "'>" + vo.piId + "</li>";
                        if (flag == 0) {
                            subMonitorViewVos.push(vo);
                        }
                        flag++;
                        //3. 将所有的值存在datamap中
                        dataMap[bcode+"<|>"+vo.piId] = vo;
                    });
                    html += '</ul></div></div> <div class="graph_detail"> <div id="' + bcode + '" class="canvas_list"></div> </div></li>';
                    $("#perf").append(html);
                    drawPerfImage(bcode, subMonitorViewVos);
                });

                //添加click事件之前先解绑上一次绑定的事件
                $('.graph_select').unbind("click");
                $(".graph_select li").unbind("click");

                $('.graph_select').click(function(){
                    $(this).find('ul').toggle();
                });
                /**
                 * 下拉菜单加入click事件
                 */
                $(".graph_select li").click(function(){
                    var bcode_piId = $(this).attr("key");
                    var vo = dataMap[bcode_piId];
                    var vos = [];
                    vos.push(vo);
                    drawPerfImage(bcode_piId.split("<|>")[0], vos);
                });
            }
        }
    })
}

//处理容量数据
function dealCapacData(resource_id){
    $("#capac").empty();
    $.ajax({
        url : webPath + "/radar/view/selectCapacData.do",
        type : "post",
        dataType : "json",
        data : {
            "resourceId" : resource_id
        },
        success : function (json) {
            var code = json.code;
            if (code == "201"){
                $("#capac").append("暂无数据");
            }else if (code == "200"){
                var voMap = json.data;
                $.each(voMap, function (bcode, voList) {
                    if(voList != null){
                        drawCapacImage(voList);
                    }
                });
            }
        }

    });
}

//处理进程数据
function dealProcessData(resource_id){
    $('#process tbody').empty();
    $('#process thead').empty();
    $.ajax({
        url: webPath + "/radar/view/selectProcessData.do?",
        type: "post",
        dataType: 'json',
        cache:false,
        data: {
            "resourceId":resource_id,
        },
        success: function (result) {
            if(result.code=="200"){
                //1 title
                var titlehtml="<tr>";
                $.each(result.data.title,function(name,value){
                    titlehtml+="<th>"+value+"</th>";
                });
                titlehtml+="</tr>";
                $('#process thead').html(titlehtml);
                //2 data
                var datahtml="";
                $.each(result.data.data,function(name,value){
                    datahtml+="<tr>";
                    $.each(result.data.title,function(becode){
                        if(value[becode]=="null" || value[becode]==null){
                            value[becode]="";
                        }
                        datahtml+="<td>"+value[becode]+"</td>";
                    });
                    datahtml+="<tr>";
                });
                $('#process tbody').html(datahtml);
            }else if(result.errorMessage=="201"){
                //无数据
                $('#process tbody').append("暂无数据");
            }else{
                $('#process tbody').append(result.errorMessage);
            }
        }
    });
}

//获取服务状态数据
function dealServiceStateData(resource_id){
    $('#servicestatus').empty();
    var columns = [{code:"serviceName", name:"服务名称"},
                   {code:"serviceMessage", name:"描述"},
                   {code:"serviceState", name:"状态"}];
    var param = {url:webPath+"/radar/view/selectServiceStateData.do", divID:"servicestatus", afterQuery:"hiddenFooterPage"};
    var data = {resourceId: resource_id};
    easyQuery(columns, param, data);
}

//隐藏页脚
function hiddenFooterPage() {
    $("#servicestatuspageMenu").css("display", "none");
}

//获取状态数据
function dealStatusData(resource_id){
    $('#status').empty();
    $.ajax({
        url: webPath + "/radar/view/selectStatusData.do",
        type: "post",
        dataType: 'json',
        cache:false,
        data: {
            "resourceId":resource_id,
        },
        success: function (result) {
            var dataSource="";
            if(result.code=="200"){
                $.each(result.data,function(key,value){
                    var critimes=value.criticalTimes;
                    var errtimes=value.errorTimes;
                    var warntimes=value.warningTimes;
                    var imageurl=value.imageUrl;
                    var partname=value.partName;
                    var partid=value.partId;
                    var allype;
                    if(critimes>0){
                        allype="cri";
                    }else{
                        if(errtimes>0){
                            allype="err";
                        }else{
                            if(warntimes>0){
                                allype="warn";
                            }else{
                                allype="normal";
                            }
                        }
                    }
                    if(allype == "cri"){
                        dataSource=dataSource+
                            '<div class="span2">'+
                            '<img src="'+webPath+"/"+imageurl+'"/>'+
                            '<span>'+partname+':</span><span style="color:#e50000;cursor:pointer;" partName="'+partname+'>'+critimes+'</span>'+
                            '<input type="hidden" value='+partid+' name="part">'+
                            '</div>';
                    }
                    if(allype == "err"){
                        dataSource=dataSource+
                            '<div class="span2">'+
                            '<img src="'+webPath+"/"+imageurl+'"/>'+
                            '<span>'+partname+':</span><span style="color:#ff5f00;cursor:pointer;" partName="'+partname+'>'+errtimes+'</span>'+
                            '<input type="hidden" value='+partid+' name="part">'+
                            '</div>';
                    }
                    if(allype == "warn"){
                        dataSource=dataSource+
                            '<div class="span2">'+
                            '<img src="'+webPath+"/"+imageurl+'"/>'+
                            '<span>'+partname+':</span><span style="color:#ffcc00;cursor:pointer;" partName="'+partname+'">'+warntimes+'</span>'+
                            '<input type="hidden" value='+partid+' name="part">'+
                            '</div>';
                    }
                    if(allype=="normal"){
                        dataSource=dataSource+
                            '<div class="span2">'+
                            '<img src="'+webPath+"/"+imageurl+'" />'+
                            '<span>'+partname+':</span><span style="color:#00ac20;"><span>正常</span>'+
                            '<input type="hidden" value='+partid+' name="part">'+
                            '</div>';
                    }
                });
            }else if(result.code=="201"){
                //无数据
                $('#status').append("暂无数据");

            }else{
                $('#status').append(result.errorMessage);
            }
            $(dataSource).appendTo("#status");
        }
    });
}

//处理数据库
function dealDBData(resource_id) {
    $("#db").empty();
    var startTime = $("#startTime").val().trim();
    var endTime = $("#endTime").val().trim();
    $.ajax({
        url:webPath+"/radar/view/selectDBData.do",
        type:'post',
        dataType:'json',
        data:{
            resourceId:resource_id,
            startTime:startTime,
            endTime:endTime
        },
        success:function (json) {
            var code = json.code;
            if (code == '200'){
                var map = json.data;
                $.each(map, function (bcode, monitorViewVos) {

                    //1.页面展示
                    var html = '<li class="capacity_list"><div class="graph_title"> <h2 style="margin: 0 10px">' + monitorViewVos[0].bcodeName + '</h2> <div class="graph_select"> <span class="selectlist">实例<a class="top_current down"></a></span> <ul>';
                    var subMonitorViewVos = [];
                    var flag = 0;
                    //2.如果bcode下面有多个piId，只展示一个
                    $.each(monitorViewVos, function (i, vo) {
                        html += "<li key='" + bcode+"<|>"+ vo.piId + "'>" + vo.piId + "</li>";
                        if (flag == 0) {
                            subMonitorViewVos.push(vo);
                        }
                        flag++;
                        //3. 将所有的值存在datamap中
                        dataMap[bcode+"<|>"+vo.piId] = vo;
                    });
                    html += '</ul></div></div> <div class="graph_detail"> <div id="' + bcode + '" class="canvas_list"></div> </div></li>';
                    $("#db").append(html);
                    drawPerfImage(bcode, subMonitorViewVos);
                });

                //不用再重新解绑和绑定click事件，click在性能方法中绑定就行了
                // $('.graph_select').unbind("click");
                // $(".graph_select li").unbind("click");
                //
                // $('.graph_select').click(function(){
                //     $(this).find('ul').toggle();
                // });
                // /**
                //  * 下拉菜单加入click事件
                //  */
                // $(".graph_select li").click(function(){
                //     var bcode_piId = $(this).attr("key");
                //     var vo = dbMap[bcode_piId];
                //     var vos = [];
                //     vos.push(vo);
                //     drawPerfImage(bcode_piId.split("<|>")[0], vos);
                // });
            } else if (code = '201'){
                $("#db").append("暂无数据");
            }else{
                $("#db").append(json.errMessage);
            }
        }
    });

}


//初始化数据
function initData() {
    var date = new Date();
    //默认展示前12个小时的数据
    date.setHours(date.getHours() - 24);
    $("#startTime").val(formatDateTime(date));
    $("#endTime").val(formatDateTime(new Date()));
}

//画ping图片
function drawPingImage(results) {
    var data = [];
    var series = [];
    var time = [];
    var myChart = echarts.init(document.getElementById("ping"));
    $.each(results, function (String, list) {
        if (String != "time") {
            data.push(String);
            var seriesData = {};
            seriesData.name = String;
            seriesData.type = "line";
            seriesData.stack = "值";
            seriesData.data = list;
            series.push(seriesData);
        } else {
            time = list;
        }
    });
    var option = {
        title :{
            text: "ping数据展示",
        },
        tooltip:{
            trigger:"axis"
        },
        legend:{
            data:data,
            x : "right"
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        // toolbox: {
        //     feature: {
        //         saveAsImage: {}
        //     }
        // },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: time
        },
        yAxis: {
            type: 'value'
        },
        series: series
    }
    myChart.setOption(option);
}

//画性能图片 (数据库图片)
function drawPerfImage(bcode, monitorViewVos)   {
    var myChart = echarts.init(document.getElementById(bcode));
    var time = null;
    var data = [];
    var series = [];

    $.each(monitorViewVos, function (i, vo) {

        var seriesData = {};
        data.push(vo.piId);
        if (time == null) {
            time = vo.times;
        }
        seriesData.name = vo.piId;
        seriesData.type = "line";
        seriesData.stack = "值";
        seriesData.data = vo.values;
        series.push(seriesData);
    });

    var option = {
        tooltip:{
            trigger:"axis"
        },
        legend:{
            data:data,
            x : "right"
        },
        grid: {
            left: '10%',
            right: '4%',
            bottom: '5%',
            containLabel: true
        },
        // toolbox: {
        //     feature: {
        //         saveAsImage: {}
        //     }
        // },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: time
        },
        yAxis: {
            type: 'value'
        },
        series: series
    }
    myChart.setOption(option);
}

//画容量图片
function drawCapacImage(parts) {
    // 获取选中的 tab panel 和它的 tab 对象
    $("#capac").html("");
    var becode = "";
    var capacArr = [];
    for(var i = 0; i < parts.length; i++){
        capacArr.push(parts[i].bcode);
    }
    becode = capacArr.join(",");
    //通过指标获取数据
    var context = '';
    if(parts.length == 0){ //数据为空
        for(var i = 0; i < parts.length; i++){
            context += '<div class="content_list">'+
                '<div class="content_condition">'+
                '<div class="control-title">'+
                '<span>'+parts[i].partsName+'</span>'+
                '<span class="redbtn">('+parts[i].bcodeName+')</span>'+
                '</div>'+
                '<div class="last_group">无数据</div> </div></div>';
        }
        $(context).appendTo("#capac");
    }else {
        //数据不为空
        for (var i = 0; i < parts.length; i++) {
            context = '<div class="content_list">' +
                '<div class="content_condition">' +
                '<div class="control-title listwidth">' +
                '<span>' + parts[i].partsName + '</span>' +
                '<span class="redbtn">(' + parts[i].bcodeName + ')</span>' +
                '</div>' +
                //柱状图设置保存区域
                '<ul class="last_group">';
                for (var j = 0; j < parts.length; j++) {
                    if (parts[i].bcode == parts[j].bcode) {
                        context += '<li class="capacity_list">' +
                            '<div id="canvas_' + parts[j].bcode + j + '" class="canvas_list"></div>' +
                            '</li>';
                    }
                }
            context += '</ul></div></div>';
            $(context).appendTo("#capac");
            //画柱状图
            for (var m = 0; m < parts.length; m++) {
                if (parts[i].bcode == parts[m].bcode) {
                    $("#canvas_" + parts[m].bcode + m).columnFlot(
                        {
                            isAnimate: true,			//是否开启动画
                            maxValue: parts[m].maxValue == null ? "" : parts[m].maxValue,	//最大值
                            targetValue: parts[m].piId_value,			//指标值
                            percent: parts[m].percent,
                            caption: parts[m].time,	//标题
                            unit: parts[m].unit,				//单位
                            title: parts[m].bcodeName,
                            diameter: 30,				//直径
                            column_color: "rgba(123,255,20,0.2)",		//容器柱体颜色
                            plug_color: "rgb(251,255,226)",		//容器顶盖颜色
                            tar_column_color: "rgb(75,173,58)",	//指标柱体颜色
                            tar_plug_color: "rgb(164,218,155)",	//指标顶盖颜色
                            isShowMaxValueTitle: parts[m].unit == '%' ? false : true
                        }
                    );
                }
            }
        }
    }
}